﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Collections.ObjectModel;
using _18miljard.Db;
using _18miljard.Mail;

namespace _18miljard.Daily
{
	public class DailyJobs
	{
		int dayHandled;

		public DailyJobs()
		{
			this.Read();
		}

		private void Read()
		{
			XmlDocument doc = new XmlDocument();

			doc.Load(HttpContext.Current.Server.MapPath("/App_Data/Daily.xml"));

			XmlNode node = doc.DocumentElement.FirstChild;

			if (node == null)
				return;

			XmlAttribute attr = node.Attributes["day"];
			if (attr != null)
			{
				this.dayHandled = XmlConvert.ToInt32(attr.Value);
			}
		}

		private bool Write()
		{
			bool success;

			DateTime dt = DateTime.Now;

			XmlDocument doc = new XmlDocument();

			XmlElement elt = doc.CreateElement("miljard");

			XmlElement date = doc.CreateElement("dayhandled");

			XmlAttribute d = doc.CreateAttribute("day");
			d.Value = XmlConvert.ToString(dt.Day);

			date.Attributes.Append(d);

			elt.AppendChild(date);

			doc.AppendChild(elt);

			try
			{
				success = true;
				doc.Save(HttpContext.Current.Server.MapPath("/App_Data/Daily.xml"));
			}
			catch
			{
				success = false;
			}

			return success;
		}

		public void Handle()
		{
			DateTime now = DateTime.Now;

			if (this.dayHandled == now.Day)
				return;

			if (this.Write() == false)
				return;

			JobScheduler scheduler = new JobScheduler();

			LogWriter.Write("Starting daily jobs...");

			scheduler.Execute();

			LogWriter.Write("Done.");

			DataCache.ClearAll();

			Global.ReleaseMail();
		}
	}
}
